const express = require('express');
const fs = require('fs');
const path = require('path');
const log4js = require('log4js');
const axios = require('axios');
const fsExtra = require('fs-extra');
const moment = require('moment');
const morgan = require('morgan');

// 全局常量
const BAK_BRANCH_NAME = 'release-bak-2503.14';

// 初始化日志目录
const logDir = path.join(__dirname, 'logs');
fsExtra.ensureDirSync(logDir);

// 删除并重建日志文件
const logFiles = ['access.log', 'access-detail.log', 'error.log', 'axios.log'];
logFiles.forEach(file => {
  const filePath = path.join(logDir, file);
  if (fs.existsSync(filePath)) {
    fs.unlinkSync(filePath);
  }
  fs.writeFileSync(filePath, '');
});

// 配置log4js
log4js.configure({
  appenders: {
    access: {
      type: 'file',
      filename: path.join(logDir, 'access.log'),
      layout: {
        type: 'pattern',
        pattern: '%d{yyyy-MM-dd hh:mm:ss} [%p] %m'
      }
    },
    accessDetail: {
      type: 'file',
      filename: path.join(logDir, 'access-detail.log'),
      layout: {
        type: 'pattern',
        pattern: '%d{yyyy-MM-dd hh:mm:ss} [%p] %m'
      }
    },
    error: {
      type: 'file',
      filename: path.join(logDir, 'error.log'),
      layout: {
        type: 'pattern',
        pattern: '%d{yyyy-MM-dd hh:mm:ss} [%p] %m'
      }
    },
    axios: {
      type: 'file',
      filename: path.join(logDir, 'axios.log'),
      layout: {
        type: 'pattern',
        pattern: '%d{yyyy-MM-dd hh:mm:ss} [%p] %m'
      }
    },
    console: {
      type: 'console'
    }
  },
  categories: {
    default: { appenders: ['console'], level: 'info' },
    access: { appenders: ['access'], level: 'info' },
    accessDetail: { appenders: ['accessDetail'], level: 'info' },
    error: { appenders: ['error', 'console'], level: 'error' },
    axios: { appenders: ['axios'], level: 'info' }
  }
});

// 创建日志记录器
const logger = log4js.getLogger();
const accessLogger = log4js.getLogger('access');
const accessDetailLogger = log4js.getLogger('accessDetail');
const errorLogger = log4js.getLogger('error');
const axiosLogger = log4js.getLogger('axios');

// 配置axios
axios.defaults.headers.common['Accept'] = '*/*';
axios.defaults.headers.common['Accept-Encoding'] = 'gzip,deflate,br';
axios.defaults.headers.common['User-Agent'] = 'Mozilla/5.0';
axios.defaults.headers.common['Connection'] = 'keep-alive';
axios.defaults.headers.common['cookie'] = 'exp=89cd78c2;c=auth';

// 添加axios请求拦截器记录日志
axios.interceptors.request.use(config => {
  axiosLogger.info(`Request: ${config.method.toUpperCase()} ${config.url}`);
  axiosLogger.info(`Request Headers: ${JSON.stringify(config.headers)}`);
  if (config.data) {
    axiosLogger.info(`Request Body: ${JSON.stringify(config.data)}`);
  }
  return config;
}, error => {
  axiosLogger.error(`Request Error: ${error.message}`);
  return Promise.reject(error);
});

// 添加axios响应拦截器记录日志
axios.interceptors.response.use(response => {
  axiosLogger.info(`Response: ${response.status} ${response.statusText}`);
  axiosLogger.info(`Response Data: ${JSON.stringify(response.data)}`);
  return response;
}, error => {
  if (error.response) {
    axiosLogger.error(`Response Error: ${error.response.status} ${error.response.statusText}`);
    axiosLogger.error(`Response Data: ${JSON.stringify(error.response.data)}`);
  } else {
    axiosLogger.error(`Response Error: ${error.message}`);
  }
  return Promise.reject(error);
});

// 创建Express应用
const app = express();

// 静态资源目录
app.use(express.static(path.join(__dirname, 'public')));

// 请求体解析
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 访问日志中间件
app.use(morgan('combined', {
  stream: {
    write: (message) => {
      accessLogger.info(message.trim());
    }
  }
}));

// 详细访问日志中间件
app.use((req, res, next) => {
  const oldSend = res.send;
  res.send = function(data) {
    const logData = {
      time: new Date().toISOString(),
      method: req.method,
      url: req.url,
      headers: req.headers,
      body: req.body,
      statusCode: res.statusCode,
      response: data
    };
    accessDetailLogger.info(JSON.stringify(logData, null, 2));
    oldSend.apply(res, arguments);
  };
  next();
});

// 路由
app.use('/api/local', require('./src/routes/local'));
app.use('/api/user', require('./src/routes/user'));

// 错误处理中间件
app.use((err, req, res, next) => {
  errorLogger.error(err.stack);
  console.error(err);
  
  res.status(500).json({
    status: 'error',
    message: err.message,
    stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
  });
});

// 404处理
app.use((req, res) => {
  res.status(404).json({
    status: 'error',
    message: 'Not Found'
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
  console.log(`Backup branch name: ${BAK_BRANCH_NAME}`);
});

module.exports = app;